# -*- coding: utf-8 -*-
# Author: Andeviln
# Date: 2025/01/6
# Version: 1.0.0
# 功能：读取Excel文件并返回数据

import openpyxl
import os
from src.config import Config


class ReadFromExcel:
    def __init__(self):
        """初始化"""
        conf = Config()
        self.file_path = conf.get(section='Paths', key='EXCEL_FILE_PATH')
        self.excel_files = {}
        self.read_all_files(self.file_path)


    def read_all_files(self,dir_path):
        """读取给定文件夹下的所有文件"""
        # 遍历dir_path目录下的所有文件
        for file_name in os.listdir(dir_path):
            # 如果文件名以.xls或.xlsx结尾
            if file_name.endswith('.xls') or file_name.endswith('.xlsx'):
                # 将文件名作为键，openpyxl.load_workbook(os.path.join(dir_path, file_name))作为值，添加到self.excel_files字典中
                # print(file_name)
                # print(os.path.join(dir_path, file_name))
                self.excel_files[file_name] = openpyxl.load_workbook(os.path.join(dir_path, file_name))



    def read_excel_by_sheet(self, sheet_name):
        if not os.path.exists(self.file_path):
            print("文件不存在！")
            return None
        try:
            workbook = openpyxl.load_workbook(self.file_path)
            sheet = workbook[sheet_name]
            data = []
            for row in sheet.rows:
                data.append([cell.value for cell in row])
            return data
        except Exception as e:
            print("读取Excel文件出错！", e)
            return None
    def read_excel_by_row(self, sheet_name, row_num):
        if not os.path.exists(self.file_path):
            print("文件不存在！")
            return None
        try:
            workbook = openpyxl.load_workbook(self.file_path)
            sheet = workbook[sheet_name]
            data = []
            for row in sheet.iter_rows(min_row=row_num, max_row=row_num, min_col=1, max_col=100):
                data.append([cell.value for cell in row])
            return data
        except Exception as e:
            print("读取Excel文件出错！", e)
            return None

if __name__ == '__main__':
    read_from_excel = ReadFromExcel()
    print(read_from_excel.excel_files)